package com.gitee.cui.websocket;

import com.gitee.cui.http.HttpProtocolHelper;
import com.gitee.cui.util.IOUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpMethod.GET;


/**
 * websocket网页处理器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/1 15:19
 **/
@Slf4j
public class WebPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

        // 校验HTTP的请求格式
        if (!msg.decoderResult().isSuccess()) {
            HttpProtocolHelper.sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }

        // 只允许GET请求
        if (!GET.equals(msg.method())) {
            HttpProtocolHelper.sendError(ctx, HttpResponseStatus.FORBIDDEN);
            return;
        }

        // 缓存HTTP协议的版本号
        HttpProtocolHelper.cacheHttpProtocol(ctx, msg);
        String content = IOUtil.loadResourceFile("index.html");
        // 发送消息
        HttpProtocolHelper.sendWebPage(ctx, content);
    }
}
